//@login & register
const express = require("express")
//路由级别中间件
const router = express.Router()
const bcrypt = require("bcrypt")
const gravatar = require('gravatar')
const jwt = require('jsonwebtoken')
const keys = require("../../config/keys")
const passport = require("passport")


const User = require("../../models/User")
//$route GET api/users/test
//@desc  返回的请求的json数据
//@access public
// router.get("/test",(req,res)=>{
//     res.json({msg:"login works"})
// })

//$route POST api/users/register
//@desc  返回的请求的json数据
//@access public
router.post("/register",(req,res)=>{
    // console.log(req.body);

    //查询数据库中是否拥有邮箱
    User.findOne({email:req.body.email})
                .then((user)=>{
                    if(user){
                        return res.json({
                            status:400,
                            message:"用户已存在！"
                        })
                    }else if(req.body.password!==req.body.password2){
                        return res.json({
                            status:400,
                            message:"两次密码不一致！"
                        })
                    }else{
                        const avatar = gravatar.url(req.body.email, {s: '200', r: 'pg', d: 'mm'});
                        const newUser = new User({
                            name:req.body.name,
                            email:req.body.email,
                            password:req.body.password,
                            avatar,
                            identity:req.body.identity,
                        })
                        bcrypt.genSalt(10, function(err, salt) {
                            bcrypt.hash(newUser.password, salt, (err, hash) => {
                                // Store hash in your password DB.
                                if(err) throw err

                                newUser.password = hash
                                newUser.save()
                                       .then(user=>res.json({
                                        user,
                                        status:200,
                                        message:"注册成功！"
                                       }))
                                       .catch(err=>console.log(err))
                            });
                        });
                    }
                })
})

//$route POST api/users/login
//@desc  返回token jwt passport
//@access public
router.post("/login",(req,res)=>{
    const email = req.body.email
    const password = req.body.password

    //查询数据库
    User.findOne({email})
        .then(user => {
            if(!user){
                return res.json({
                    status:404,
                    message:"用户不存在，请注册！",
                })
            }

            //密码匹配
            bcrypt.compare(password, user.password)
                  .then(isMatch => {
                    if(isMatch){
                        //jwt.sign("规则","加密名字","过期时间","箭头函数")
                        const rule = {
                            id:user.id,
                            email:user.email,
                            avatar:user.avatar,
                            identity:user.identity
                        }
                        jwt.sign(rule,keys.secretOrKey,{expiresIn:3600*24},(err,token)=>{
                            if(err) throw err
                            res.json({
                                success:true,
                                //token:"linan" + token一定要按照下面方式写
                                token:"Bearer " + token,
                                status:200,
                                message:"登录成功！",
                                email:user.email
                            })
                        })
                        //res.json({msg:"success"})
                    }else{
                        return res.json({
                            status:400,
                            message:"密码错误,请重新输入！",
                        })
                    }
                  })
        })
})

//$route GET api/users/current
//@desc  return current user
//@access Private
router.get("/current",passport.authenticate("jwt",{session:false}),(req,res) => {
    res.json({
        id:req.user.id,
        name:req.user.name,
        email:req.user.email,
        identity:req.user.identity
    })
})

module.exports = router